package com.yixin.token;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class TestEncrpt {
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {

        String plainText = "Hello, world!";
        String key = "12345678";
        // Convert the key into bytes
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        // Create the key specification
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "DES");
        // Create the cipher and initialize it for encryption
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        // Encrypt the plaintext
        byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        // Print the ciphertext
        System.out.println("Ciphertext: " + new String(cipherText, StandardCharsets.UTF_8));
        // Initialize the cipher for decryption
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        // Decrypt the ciphertext
        byte[] decryptedText = cipher.doFinal(cipherText);
        // Print the decrypted text
        System.out.println("Decrypted text: " + new String(decryptedText, StandardCharsets.UTF_8));
    }
}